<?php

namespace app\admin\service;

use app\admin\model\UM as UM;
use ShidianUtil\Exception\DataNotExistException;
use app\admin\dao\ConsultingCommentDao;
use app\common\model\ConsultingComment;
use ShidianUtil\Utils\TimeUtil;
use think\Collection;

/**
 * Class CommentService
 * @package app\admin\service
 */
class CommentService
{
    // dao
    private ConsultingCommentDao $consultingCommentDao;

    public function __construct(ConsultingCommentDao $consultingCommentDao)
    {
        $this->consultingCommentDao = $consultingCommentDao;
    }

    /**
     * @param UM|null $user
     * @param $startTime
     * @param $endTime
     * @param $kw
     * @param int|null $page
     * @param int|null $page_size
     * @return array
     */
    public function index(?UM $user, $startTime, $endTime, $kw, ?int $page = null, ?int $page_size = null): array
    {
        if(is_numeric($endTime)){
            $endTime = TimeUtil::stamp(TimeUtil::DAY, $endTime, false);
        }
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->consultingCommentDao->listComment($startTime, $endTime, $kw, $page, $page_size);
    }

    /**
     * 查询
     * @param UM|null $user
     * @param int $id
     * @return ConsultingComment
     */
    public function read(?UM $user, int $id): ?ConsultingComment
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->consultingCommentDao->findByPK($id, true);
    }

    /**
     * 新增
     * @param UM $user
     * @param array $params
     * @return  ConsultingComment
     */
    public function add(UM $user, array $params): ConsultingComment
    {
        return $this->consultingCommentDao->insertActive($params, []);
    }

    /**
     * 更新
     * @param UM  $user
     * @param int   $id
     * @param array $params
     * @return ConsultingComment
     */
    public function modify(UM $user, int $id, array $params): ConsultingComment
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = ConsultingComment::field(true)->where('id', $id)->find();

        if(is_null($record)){
            throw new DataNotExistException('该对象不存在或已被删除');
        }

        $allowField = [];
        $this->consultingCommentDao->updateActive($record, $params, $allowField);

        return $record;
    }

    /**
     * 删除
     * @param UM $user
     * @param int $id
     */
    public function rm(UM $user, int $id): void
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = ConsultingComment::field(true)->where('id', $id)->find();

         if (is_null($record)) {
             return;
         }

        $this->consultingCommentDao->deleteModel($record);
    }

}
